import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Space,
  Tag,
  Modal,
  Form,
  Input,
  Tree,
  message,
  Card,
  Row,
  Col,
  Popconfirm,
  Tabs,
  List,
  Avatar
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SafetyOutlined,
  UserOutlined,
  SearchOutlined
} from '@ant-design/icons';
import { roleAPI, adminUserAPI } from '../../services/api';
import { permissions } from '../../services/mockData';

const { TextArea } = Input;
const { TabPane } = Tabs;

const AdminRoles = () => {
  const [loading, setLoading] = useState(false);
  const [roles, setRoles] = useState([]);
  const [adminUsers, setAdminUsers] = useState([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [userModalVisible, setUserModalVisible] = useState(false);
  const [editingRole, setEditingRole] = useState(null);
  const [selectedRole, setSelectedRole] = useState(null);
  const [roleForm] = Form.useForm();

  // 统一的按钮样式
  const buttonStyle = {
    height: '32px',
    fontSize: '14px',
    fontWeight: '400',
    borderRadius: '6px'
  };

  useEffect(() => {
    loadRoles();
    loadAdminUsers();
  }, []);

  const loadRoles = async () => {
    setLoading(true);
    try {
      const response = await roleAPI.getRoles();
      if (response.success) {
        setRoles(response.data);
      }
    } catch (error) {
      message.error('加载角色列表失败');
    } finally {
      setLoading(false);
    }
  };

  const loadAdminUsers = async () => {
    try {
      const response = await adminUserAPI.getAdminUsers({ pageSize: 100 });
      if (response.success) {
        setAdminUsers(response.data.list);
      }
    } catch (error) {
      console.error('加载管理员列表失败:', error);
    }
  };

  const handleAdd = () => {
    setEditingRole(null);
    roleForm.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (record) => {
    setEditingRole(record);
    roleForm.setFieldsValue({
      ...record,
      permissions: record.permissions || []
    });
    setModalVisible(true);
  };

  const handleDelete = async (id) => {
    try {
      const response = await roleAPI.deleteRole(id);
      if (response.success) {
        message.success('删除成功');
        loadRoles();
      } else {
        message.error(response.message);
      }
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleViewUsers = (role) => {
    setSelectedRole(role);
    setUserModalVisible(true);
  };

  const handleSubmit = async () => {
    try {
      const values = await roleForm.validateFields();
      
      let response;
      if (editingRole) {
        response = await roleAPI.updateRole(editingRole.id, values);
      } else {
        response = await roleAPI.addRole(values);
      }

      if (response.success) {
        message.success(editingRole ? '更新成功' : '添加成功');
        setModalVisible(false);
        loadRoles();
      } else {
        message.error(response.message);
      }
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 构建权限树数据
  const buildPermissionTree = () => {
    return permissions.map(module => ({
      title: module.name,
      key: module.code,
      children: module.children?.map(item => ({
        title: item.name,
        key: item.code,
      })) || []
    }));
  };

  const columns = [
    {
      title: '角色信息',
      key: 'roleInfo',
      render: (_, record) => (
        <div>
          <div style={{ fontWeight: 'bold', fontSize: '14px' }}>{record.name}</div>
          <div style={{ fontSize: '12px', color: '#999' }}>{record.code}</div>
        </div>
      ),
    },
    {
      title: '权限数量',
      dataIndex: 'permissions',
      key: 'permissionCount',
      render: (permissions) => (
        <Tag color="blue">{permissions?.length || 0} 个权限</Tag>
      ),
    },
    {
      title: '用户数量',
      key: 'userCount',
      render: (_, record) => {
        const userCount = adminUsers.filter(user => 
          user.roles?.some(role => role.id === record.id)
        ).length;
        return <Tag color="green">{userCount} 个用户</Tag>;
      },
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
      render: (description) => description || '-',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (time) => time ? new Date(time).toLocaleDateString() : '-',
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 250,
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            icon={<UserOutlined />}
            size="small"
            onClick={() => handleViewUsers(record)}
            style={buttonStyle}
          >
            查看用户
          </Button>
          
          <Button
            type="link"
            icon={<EditOutlined />}
            size="small"
            onClick={() => handleEdit(record)}
            style={buttonStyle}
          >
            编辑
          </Button>
          
          {record.code !== 'super_admin' && (
            <Popconfirm
              title="确定要删除这个角色吗？"
              description="删除后拥有该角色的用户将失去相应权限"
              onConfirm={() => handleDelete(record.id)}
            >
              <Button
                type="link"
                danger
                icon={<DeleteOutlined />}
                size="small"
                style={buttonStyle}
              >
                删除
              </Button>
            </Popconfirm>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card
        title={
          <Space>
            <SafetyOutlined />
            <span>角色权限管理</span>
          </Space>
        }
        extra={
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleAdd}
            style={buttonStyle}
          >
            添加角色
          </Button>
        }
      >
        <Table
          columns={columns}
          dataSource={roles}
          rowKey="id"
          loading={loading}
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
        />
      </Card>

      {/* 角色编辑模态框 */}
      <Modal
        title={
          <Space>
            <SafetyOutlined />
            <span>{editingRole ? '编辑角色' : '添加角色'}</span>
          </Space>
        }
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
        width={800}
        destroyOnClose
        okButtonProps={{ style: buttonStyle }}
        cancelButtonProps={{ style: buttonStyle }}
      >
        <Form
          form={roleForm}
          layout="vertical"
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="角色名称"
                rules={[{ required: true, message: '请输入角色名称' }]}
              >
                <Input placeholder="请输入角色名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="code"
                label="角色编码"
                rules={[
                  { required: true, message: '请输入角色编码' },
                  { pattern: /^[a-zA-Z_][a-zA-Z0-9_]*$/, message: '编码只能包含字母、数字和下划线，且不能以数字开头' }
                ]}
              >
                <Input 
                  placeholder="请输入角色编码（如：product_admin）"
                  disabled={editingRole?.code === 'super_admin'}
                />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="description"
            label="角色描述"
          >
            <TextArea
              rows={3}
              placeholder="请输入角色描述"
            />
          </Form.Item>

          <Form.Item
            name="permissions"
            label="权限配置"
            rules={[{ required: true, message: '请至少选择一个权限' }]}
          >
            <Tree
              checkable
              treeData={buildPermissionTree()}
              height={300}
              style={{ 
                border: '1px solid #d9d9d9',
                borderRadius: 6,
                padding: 8
              }}
            />
          </Form.Item>
        </Form>
      </Modal>

      {/* 角色用户列表模态框 */}
      <Modal
        title={
          <Space>
            <UserOutlined />
            <span>{selectedRole?.name} - 用户列表</span>
          </Space>
        }
        open={userModalVisible}
        onCancel={() => setUserModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setUserModalVisible(false)} style={buttonStyle}>
            关闭
          </Button>
        ]}
        width={600}
      >
        {selectedRole && (
          <div>
            <div style={{ 
              padding: '16px', 
              backgroundColor: '#f5f5f5', 
              borderRadius: '6px', 
              marginBottom: '16px' 
            }}>
              <Row gutter={16}>
                <Col span={12}>
                  <div><strong>角色名称：</strong>{selectedRole.name}</div>
                  <div><strong>角色编码：</strong>{selectedRole.code}</div>
                </Col>
                <Col span={12}>
                  <div><strong>权限数量：</strong>{selectedRole.permissions?.length || 0} 个</div>
                  <div><strong>描述：</strong>{selectedRole.description || '-'}</div>
                </Col>
              </Row>
            </div>
            
            <List
              itemLayout="horizontal"
              dataSource={adminUsers.filter(user => 
                user.roles?.some(role => role.id === selectedRole.id)
              )}
              renderItem={user => (
                <List.Item>
                  <List.Item.Meta
                    avatar={
                      <Avatar 
                        icon={<UserOutlined />} 
                        src={user.avatar}
                        style={{ backgroundColor: '#1890ff' }}
                      />
                    }
                    title={
                      <Space>
                        <span>{user.nickname || user.username}</span>
                        <Tag color={user.status === 'active' ? 'green' : 'red'}>
                          {user.status === 'active' ? '正常' : '禁用'}
                        </Tag>
                      </Space>
                    }
                    description={
                      <div>
                        <div>用户名: {user.username}</div>
                        <div>邮箱: {user.email || '-'}</div>
                        <div>最后登录: {user.lastLoginTime ? 
                          new Date(user.lastLoginTime).toLocaleString() : '从未登录'}</div>
                      </div>
                    }
                  />
                </List.Item>
              )}
              locale={{ 
                emptyText: (
                  <div style={{ padding: '20px', textAlign: 'center', color: '#999' }}>
                    该角色下暂无用户
                  </div>
                )
              }}
            />
          </div>
        )}
      </Modal>
    </div>
  );
};

export default AdminRoles;